<?php

namespace app\admin\controller\user;

use app\admin\library\Brand as Brandserver;
use app\common\controller\Backend;
use app\common\model\Member as MemberModel;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use fast\Tree;
use think\Db;

/**
 * 用户管理
 *
 * @icon fa fa-user
 */
class Member extends Backend
{

    protected $relationSearch = true;


    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    // public function imports(){
    //     return parent::imports();
    // }
	// protected $multiFields = ['is_enable'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Member');
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->field('id')
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                // ->field('id,username,mobile,money,app_key,app_secret,sort,joinip,status,pid,brand_name')
                ->select();
			// halt($list);
			// halt($this->model->getLastSql());
            // foreach ($list as $k => $v) {
            //     $v->hidden(['password', 'salt']);
            //     $v['father']=Brandserver::brandFa($v['pid']);
            // }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
	public function add($ids = NULL){
	
	    if ($this->request->isPost()) {
	        $params = $this->request->post("row/a");
	        if ($params) {
	            $params = $this->preExcludeFields($params);
	    
	            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
	                $params[$this->dataLimitField] = $this->auth->id;
	            }
	            // 启动事务
	            Db::startTrans();
	            try {
	                //添加商品表
	                $params['jointime'] = time();
	                $params['createtime'] = time();
	                $result = $this->model->insertGetId($params);
	                // 提交事务
	                Db::commit();
	            } catch (ValidateException $e) {
	                Db::rollback();
	                $this->error($e->getMessage());
	            } catch (PDOException $e) {
	                Db::rollback();
	                $this->error($e->getMessage());
	            } catch (Exception $e) {
	                Db::rollback();
	                $this->error($e->getMessage());
	            }
	            if ($result !== false) {
	                $this->success();
	            } else {
	                $this->error(__('No rows were updated'));
	            }
	        }
	        $this->error(__('Parameter %s can not be empty', ''));
	    }
	    return $this->view->fetch();
	}
	/**
	 * 编辑
	 */
	public function edit($ids = null)
	{
	    $row = $this->model->get($ids);
	    if (!$row) {
	        $this->error(__('No Results were found'));
	    }
	    $adminIds = $this->getDataLimitAdminIds();
	    if (is_array($adminIds)) {
	        if (!in_array($row[$this->dataLimitField], $adminIds)) {
	            $this->error(__('You have no permission'));
	        }
	    }
	    if ($this->request->isPost()) {
	        $params = $this->request->post("row/a");
	        if ($params) {
	            $params = $this->preExcludeFields($params);
	            $result = false;
	            Db::startTrans();
	            try {
					//添加商品表
					$params['updatetime'] = time();
					$result = $this->model->where('id',$row['id'])->update($params);
	                Db::commit();
	            } catch (ValidateException $e) {
	                Db::rollback();
	                $this->error($e->getMessage());
	            } catch (PDOException $e) {
	                Db::rollback();
	                $this->error($e->getMessage());
	            } catch (Exception $e) {
	                Db::rollback();
	                $this->error($e->getMessage());
	            }
	            if ($result !== false) {
	                $this->success();
	            } else {
	                $this->error(__('No rows were updated'));
	            }
	        }
	        $this->error(__('Parameter %s can not be empty', ''));
	    }
	    $this->view->assign("row", $row);
		//查找规格属性表信息
		// $attr = Db::name('surprised_goods_attr')->where('surprised_goods_id',$row['id'])->select();
		// $this->view->assign("attr", $attr);
	    return $this->view->fetch();
	}
	public function import(){
	    
		set_time_limit(0);
		$savename = $this->request->post("file");
		// $file = $_SERVER['DOCUMENT_ROOT'].'/uploads'.'/'.date('Ymd').'/'.$file;
		// dump($savename);
		if (!$savename) $this->error('上传文件不能为空');
		$fileExtendName = substr(strrchr($savename, '.'), 1);
		// 有Xls和Xlsx格式两种
		if ($fileExtendName == 'xlsx') {
			$objReader = IOFactory::createReader('Xlsx');
		} else {
			$objReader = IOFactory::createReader('Xls');
		}
		// 设置文件为只读
		$objReader->setReadDataOnly(TRUE);
		// 读取文件，tp6默认上传的文件，在runtime的相应目录下，可根据实际情况自己更改
		$objPHPExcel = $objReader->load($_SERVER['DOCUMENT_ROOT'].'/uploads'.'/'.date('Ymd').'/'.$savename);
		//excel中的第一张sheet
		$sheet = $objPHPExcel->getSheet(0);
		// 取得总行数
		$highestRow = $sheet->getHighestRow();
		// 取得总列数
		$highestColumn = $sheet->getHighestColumn();
		Coordinate::columnIndexFromString($highestColumn);
		$lines = $highestRow - 1;
		if ($lines <= 0) {
			return "数据为空数组";
		}
		// 直接取出excle中的数据
		$data = $objPHPExcel->getActiveSheet()->toArray();
		// 删除第一个元素（表头）
		array_shift($data);
		//删除文件
		unlink($_SERVER['DOCUMENT_ROOT'].'/uploads'.'/'.date('Ymd').'/'.$savename);
		foreach ($data as $k => $v) {
			//判断手机号是否存在
			$isFind = Db::name('member')->where(['mobile' => $v[1]])->find();
			if(!$isFind){
				//这个员工不存在才添加 存在就不添加了
				$datas = [
					'username' => $v[0],
					'mobile' => $v[1],
					'induction_time' => strtotime($v[2]),
					'integral' => $v[3],
					'type' => 2,
					'receive' => 1,
					'createtime' => time(),
				];
				$ret = Db::name('member')->insertGetId($datas);
				if($ret){
					//增加初始积分
					$record['member_id'] = $ret;
					$record['mobile'] = $v[1];
					//默认是一百
					$record['score'] = $v[3];
					$record['type'] = 1;
					$record['integral'] = $v[3];
					$record['content'] = '发放积分';
					$record['createtime'] = time();
					$result = Db::name('member_integral_record')->insert($record);
				}
			}
			
		}
		// $ret = Db::name('staff')->insertAll($data,false,1000);
		if (isset($ret)) {
		    $this->success('导入成功');
		} else {
		    $this->error('导入失败');
		}
	}
	//发放本月积分
	public function grant(){
		//给集成员工发放积分
		$list = Db::name('member')->where('type',2)->where('receive',1)->select();
		$month = date('Y-m');
		$firstday = date('Y-m-01', strtotime($month));
		$lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
		$where['createtime'] = array('between',[strtotime($month),strtotime($lastday)]);
		//默认是增加的
		$where['type'] = array('eq',1);
		// halt($where);
		$a = 0;
		foreach($list as $key => $value){
			//判断当月是否已经发放过积分
			$where['mobile'] = array('eq',$value['mobile']);
			$isFind = Db::name('member_integral_record')->where($where)->find();
			if(!$isFind){
				$data['member_id'] = $value['id'];
				$data['mobile'] = $value['mobile'];
				//默认是一百
				$data['score'] = 100;
				$data['type'] = 1;
				$data['integral'] = $value['integral'] + $data['score'];
				$data['content'] = '发放积分';
				$data['createtime'] = time();
				$result = Db::name('member_integral_record')->insert($data);
				if($result){
					//增加用户积分
					$a = Db::name('member')->where('id',$value['id'])->update(['integral'=>$data['integral']]);
					//发放成功之后判断这个用户是否欠积分欠的话 在扣了
					// $order = Db::name('integral_order')->where('member_id',$value['id'])->where('is_adequate',2)->where('is_del',1)->find();
					// if($order){
					// 	//扣除积分
					// 	$info = Db::name('member')->where('id',$value['id'])->find();
					// 	if($info['integral'] >= $order['surplus_integral']){
					// 		//当给的积分大于所要还的积分说明这次还了之后就不用还了
					// 		$da['is_adequate'] = 1;
					// 		$da['actual_pay_integral'] = $order['actual_pay_integral'] + $order['surplus_integral'];
					// 		$da['surplus_integral'] = 0;
					// 		$actual_pay_integral =  $order['surplus_integral'];
					// 	}else{
					// 		//实际支付
					// 		$da['actual_pay_integral'] = $order['actual_pay_integral'] + $info['integral'];
					// 		$da['surplus_integral'] = $order['surplus_integral'] - $info['integral'];
					// 		$actual_pay_integral = $info['integral'];
					// 	}
					// 	// halt($da);
					// 	Db::name('integral_order')->where('order_no',$order['order_no'])->update($da);
					// 	//增加支付记录
					// 	$p_data['member_id'] = $value['id'];
					// 	$p_data['mobile'] = $value['mobile'];
					// 	$p_data['score'] = $actual_pay_integral;
					// 	$p_data['type'] = 2;
					// 	$p_data['content'] = '还欠套房的积分';
					// 	$p_data['integral'] = $info['integral'] - $actual_pay_integral;
					// 	$p_data['createtime'] = $_SERVER['REQUEST_TIME'];
					// 	$res = Db::name('member_integral_record')->insert($p_data);
					// 	if($res){
					// 		//修改个人积分
					// 		Db::name('member')->where('id',$value['id'])->update(['integral'=>$p_data['integral']]);
					// 	}
					// }
				}
			}
		}
		if($a > 0){
			 $this->success('操作成功');
		}else{
			 $this->error('发放失败');
		}
	}
}
